import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:interrogation/src/data/models/get_article_res.dart';

import '../../../../base/utils/logger.dart';
import '../../../../data/api.dart';

class NewsListController extends GetxController {
  //TODO: Implement NewsListController

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    onRefresh();
  }

  @override
  void onClose() {
    super.onClose();
  }



  //////////////////////////////////refresh/////////////////////////////////////

  var list = [].obs;

  ///refresh
  EasyRefreshController refreshController = EasyRefreshController(
      controlFinishLoad: true, controlFinishRefresh: true);
  int num = 0;
  int page = 1;
  int pageSize = 20;

  Future<void> onRefresh() async {
    try {
      page = 1;
      EasyLoading.show(status: 'loading...');
      List<ArticleModel>? _list = await Api.getArticleList(
        page: page,
        pageSize: pageSize,
      );
      if (_list != null) {
        num = _list.length;
        list.value = [..._list];
      }
    } catch (e) {
      loggy.error(e.toString());
    } finally {
      refreshController.finishRefresh();
      refreshController.resetHeader();
      EasyLoading.dismiss();
    }
  }

  Future<void> onLoad() async {
    try {
      page++;
      EasyLoading.show(status: 'loading...');
      List<ArticleModel>? _list = await Api.getArticleList(
        page: page,
        pageSize: pageSize,
      );
      if (_list != null) {
        num = _list.length;
        list.value = [...list.value, ..._list];
      }
    } catch (e) {
      loggy.error(e.toString());
    } finally {
      refreshController.finishLoad(
          num >= 20 ? IndicatorResult.success : IndicatorResult.noMore);
      refreshController.resetFooter();
      EasyLoading.dismiss();
    }
  }

//////////////////////////////////refresh/////////////////////////////////////
}
